package com.wfcm.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wfcm.annotation.IgnoreToken;
import com.wfcm.cloopen.CCPRestSmsSDK;
import com.wfcm.entity.WfPhoneCodeEntity;
import com.wfcm.service.WfPhoneCodeService;
import com.wfcm.utils.R;
import com.wfcm.utils.WebUtils;

@Controller
@RequestMapping("/send")
@ResponseBody
public class SendPhoneMessage {
	
	private Logger log = LoggerFactory.getLogger(AdInfoController.class);
	
	@Autowired
	private WfPhoneCodeService phoneCodeService; 
	
	 /**
	 * 获取验证码
	 */
	@RequestMapping("/sendMessage")
	@ResponseBody
	@IgnoreToken
	public R sendMessage(HttpServletRequest req){
		HashMap<String, Object> result = null;

		//初始化SDK
		CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
		
		//*初始化服务器地址和端口                                                       *
		//*沙盒环境（用于应用开发调试）：restAPI.init("sandboxapp.cloopen.com", "8883");*
		//*生产环境（用户应用上线使用）：restAPI.init("app.cloopen.com", "8883");       *
		//*******************************************************************************
		restAPI.init("app.cloopen.com", "8883");
		//restAPI.init("sandboxapp.cloopen.com", "8883");
		//******************************注释*********************************************
		//*初始化主帐号和主帐号令牌,对应官网开发者主账号下的ACCOUNT SID和AUTH TOKEN     *
		//*参数顺序：第一个参数是ACOUNT SID，第二个参数是AUTH TOKEN。                   *
		//*******************************************************************************
		restAPI.setAccount("8aaf0708591b6f1c01591f9cc32102bb", "c3b76516852c432d98fb130867149556");
		
		//*初始化应用ID                                                                 *
		//*测试开发可使用“测试Demo”的APP ID，正式上线需要使用自己创建的应用的App ID     *
		//*******************************************************************************
		//restAPI.setAppId("8aaf0708591b6f1c01591f9cc4b302c0");
		restAPI.setAppId("8a216da861033c5d01610d6951df0581");
		//*调用发送模板短信的接口发送短信                                                                  *
		//*假设您用测试Demo的APP ID，则需使用默认模板ID 1，发送手机号是13800000000，传入参数为6532和5，则调用方式为           *
		//*result = restAPI.sendTemplateSMS("13800000000","1" ,new String[]{"6532","5"});																		  *
		//*则13800000000手机号收到的短信内容是：【云通讯】您使用的是云通讯短信模板，您的验证码是6532，请于5分钟内正确输入     *
		//*********************************************************************************************************************
		
		String mobile =  req.getParameter("mobile");//获取手机号
 		log.debug("tel:"+mobile);
 		
		String captcha = WebUtils.getCapacha();
		//result = restAPI.sendTemplateSMS(mobile,"1" ,new String[]{captcha,"2"});
		result = restAPI.sendTemplateSMS(mobile,"233877" ,new String[]{captcha,"2分钟"});
		//保存手机号和验证码
		Map<String,Object> map =new  HashMap<String,Object>();
		map.put("mobile", mobile);
		List<WfPhoneCodeEntity> phoneCodeList =  phoneCodeService.queryList(map);
		if(phoneCodeList.size() == 0 ) {
			WfPhoneCodeEntity phoneCodeEntity = new WfPhoneCodeEntity();
			phoneCodeEntity.setCode(captcha);
			phoneCodeEntity.setPhone(mobile);
			//Long now = new Date().getTime();//当前时间戳
			phoneCodeEntity.setSendTime(getSecondTimestampTwo(new Date()));
			phoneCodeService.save(phoneCodeEntity);
		}else {
			WfPhoneCodeEntity phoneCodeEntity = phoneCodeList.get(0);
			phoneCodeEntity.setCode(captcha);
			//Long now = new Date().getTime();//当前时间戳
			phoneCodeEntity.setSendTime(getSecondTimestampTwo(new Date()));
			phoneCodeService.update(phoneCodeEntity);
		}
		
		int statusCode = Integer.valueOf((String) result.get("statusCode"));
		String statusMsg =  (String) result.get("statusMsg");
		System.out.println("SDKTestGetSubAccounts result=" + result);
		if("000000".equals(result.get("statusCode"))){
			//正常返回输出data包体信息（map）
			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");		
			/*Set<String> keySet = data.keySet();
			for(String key:keySet){
				Object object = data.get(key);
				System.out.println(key +" = "+object);
			}*/
		}else{
			//异常返回输出错误码和错误信息
			//System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
			System.out.println("错误码=" + statusCode +" ;错误信息= "+statusMsg);
			return R.error(statusCode, statusMsg);
			
		}
		return R.ok();
		
	}


	//抽奖活动
	public static void sendMes(String tel,String money,String good,String code,String endDay,String luckDay){
		CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
		restAPI.init("app.cloopen.com", "8883");
		restAPI.setAccount("8aaf0708591b6f1c01591f9cc32102bb", "c3b76516852c432d98fb130867149556");
		restAPI.setAppId("8a216da85982d9da01598719b1c901e2");
		HashMap<String, Object> result = restAPI.sendTemplateSMS(tel, "365731", new String[]{money, good, code, endDay, luckDay});
		System.out.println(new Gson().toJson(result));

	}

	/** 
	 * 获取精确到秒的时间戳 
	 * @param date 
	 * @return 
	 */  
	public static int getSecondTimestampTwo(Date date){  
	    if (null == date) {  
	        return 0;  
	    }  
	    String timestamp = String.valueOf(date.getTime()/1000);  
	    return Integer.valueOf(timestamp);  
	}  
}
